#include "LoadMenu.h"
#include "MenuManager.h"
#include "PrintUtils.h"
#include "GameControls.h"
#include "console.h"

#include <sstream>
#include <fstream>
#include <sys/stat.h>
#include <time.h>
#include <algorithm>

using namespace std;

void LoadMenu::CalculateSlots() const {
	for(size_t i = 0; i < Consts::NUM_SAVE_SLOT; ++i) 	{
		std::stringstream ss;
		ss << "./save/save_" << i << ".txt";

		std::fstream f(ss.str().c_str(), std::ios_base::in);

		slots_[i] = f.is_open();

		if (slots_[i]) { 
			struct _stat s;
			_stat(ss.str().c_str(), &s);
			
			char timebuf[26];
			ctime_s(timebuf, 26, &s.st_mtime);

			save_names_[i] = string(timebuf, timebuf+24);
		}

		f.close();
	}
}

Menu* LoadMenu::Input(const Inputs& input) {
	for (const auto& i : input) {
		if (i.type_ == INPUT_KEY_PRESSED) {
			if (i.content_ == K_ESCAPE) {
				GetMM()->PopMenu();
				return GetMM()->GetCurrentMenu();
			}
		}
		else if (i.type_ == INPUT_MOUSE_LCLICK && i.content_ != Console::NO_ENTRY){
			if (i.content_ == options_[Consts::NUM_SAVE_SLOT]) {
				GetMM()->PopMenu();
				return GetMM()->GetCurrentMenu();
			} else {
				for (int it = 0; it != Consts::NUM_SAVE_SLOT; ++it) {
					if (i.content_ == options_[it]) {
						std::stringstream ss;
						ss << "./save/save_" << it << ".txt";
						if (!GetMM()->GetGameControls()->Load(ss.str().c_str())) {
							return 0;
						}
						GetMM()->SetMenu(GetMM()->GetMainMenu());
						return GetMM()->GetCurrentMenu();
					}
				}
			}
		}
	}
	return GetMM()->GetCurrentMenu();
}

void LoadMenu::Draw(Console& console) const {
	CalculateSlots();

	PrintTitle(console, " LOAD MENU");

	for (int i = 0; i < Consts::NUM_SAVE_SLOT; ++i) {
		options_[i] = slots_[i] ? WriteString(console, 10 + 2 * i, 10, save_names_[i]) : Console::NO_ENTRY;
	}

	options_[Consts::NUM_SAVE_SLOT] = WriteString(console, 10 + 2 * Consts::NUM_SAVE_SLOT + 1, 10, "Return to previous menu");
}
